#include "database.h"
#include "stack.h"
int cd_command(MYSQL* conn, DirStack* stack, const char* path, const char* user_name) {
    if (strcmp(path, "..") == 0) {
        if (stack->top <= 0) return -1; // 根目录不能再 pop
        return pop(stack);
    } else if (strcmp(path, ".") == 0) {
        return 0;
    } else if (strcmp(path, "/") == 0) {
        stack->top = 0;
        return 0;
    } else if (strchr(path, '/')) {
        DirStack temp;
        if (path[0] == '/') {
           temp.top = 0;

    int user_root_id;
    if (get_user_root_id(conn, user_name, &user_root_id) != 0) {
        return -1; // 无法获取该用户的根目录
    }

    temp.dirs[0] = user_root_id;
}
        else {
            temp = *stack;
        }

        char path_copy[256];
        strncpy(path_copy, path, sizeof(path_copy) - 1);
        path_copy[sizeof(path_copy) - 1] = '\0';

        char* token = strtok(path_copy, "/");
        while (token) {
            if (strcmp(token, "..") == 0) {
                if (temp.top > 0)
                    temp.top--;
                else{
                        return -1;
                    }
            } else if (strcmp(token, ".") == 0) {
                // 跳过
            } else {
                int next_id, is_dir;
                if (get_id_and_isdir_by_name(conn, token, temp.dirs[temp.top], user_name, &next_id, &is_dir) != 0)
                    return -1;
                if (!is_dir) return -1;
                if (push(&temp, next_id) != 0)
                    return -1;
            }
            token = strtok(NULL, "/");
        }

        *stack = temp;
        return 0;
    } else {
        // 单层目录名
        int curr;
        if (get_top(stack, &curr) != 0) return -1;
        int next_id, is_dir;
        if (get_id_and_isdir_by_name(conn, path, curr, user_name, &next_id, &is_dir) != 0)
            return -1;
        if (!is_dir) return -1;
        return push(stack, next_id);
    }
}

